import router from '@/router'
import axios from 'axios'
import { Loading, Message } from 'element-ui'

axios.defaults.baseURL = 'http://yaonan.songshuai.dev.songshuai.com';
// 超时时间
axios.defaults.timeout = 5000
// 设置Content-Type类型
axios.defaults.headers.post['Content-Type'] = "application/json; charset=UTF-8";

//http请求拦截器
var loadinginstace
axios.interceptors.request.use(config => {
    let token = sessionStorage.getItem('YX-TOKEN');
    if(token){
        config.headers.common['YX-TOKEN'] = token;
    }
  // element ui Loading方法
  loadinginstace = Loading.service({
    // target: '.banner-middle,.main-box',
    fullscreen: true,
    text: '拼命加载中...'
  })
  return config
}, error => {
  loadinginstace.close()
  Message.error({
    message: '加载超时'
  })
  return Promise.reject(error)
})
// http响应拦截器
axios.interceptors.response.use(data => { // 响应成功关闭loading
  loadinginstace.close()
  return data
}, error => {
  loadinginstace.close()
  Message.error({
    message: '网络不给力呀！请稍候再试'
  })
  return Promise.reject(error)
  })

export default class CourseAxios {
    constructor(options = {}) {
        this.options = options;
    }

    request(options) {
        return axios.request(options);
    }

    get(url, options = {}) {
        return this.request({
            url,
            params: {
                ...options
            },
            // cancelToken: new CancelToken(c => {
            //     cancel = c
            // })
        })
    }

    post(url, data, options = {}) {
        if (data instanceof Object) {
            data = JSON.stringify(data);
        }
        return this.request({
            method: 'post',
            url,
            data,
            // cancelToken: new CancelToken(c => {
            //     cancel = c
            // }),
            ...options
        });
    }
}
const instanceAxios = new CourseAxios;
export const request = instanceAxios.request.bind(instanceAxios);
export const get = instanceAxios.get.bind(instanceAxios);
export const post = instanceAxios.post.bind(instanceAxios);
